package com.dbky.alg.browser;

import com.dbky.alg.browser.support.SimpleResponse;
import com.dbky.alg.core.properties.AlgSecurityProperties;
import com.dbky.alg.core.properties.LoginType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: tianchao
 * @Date: 2021/12/11 15:35
 * @Description:
 */
public class CustomerAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AlgSecurityProperties securityPropertiese;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
//        ApiResult result;
//        if (exception instanceof UsernameNotFoundException || exception instanceof BadCredentialsException) {
//            result = ApiResult.fail(exception.getMessage());
//        } else if (exception instanceof LockedException) {
//            result = ApiResult.fail("账户被锁定，请联系管理员!");
//        } else if (exception instanceof CredentialsExpiredException) {
//            result = ApiResult.fail("证书过期，请联系管理员!");
//        } else if (exception instanceof AccountExpiredException) {
//            result = ApiResult.fail("账户过期，请联系管理员!");
//        } else if (exception instanceof DisabledException) {
//            result = ApiResult.fail("账户被禁用，请联系管理员!");
//        } else if(exception instanceof ValidateCodeException){
//            result = ApiResult.fail(exception.getMessage());
//        } else {
//            logger.error("登录失败：", exception);
//            result = ApiResult.fail("登录失败!");
//        }
//        ResponseUtils.out(response, result);
        logger.info("登录失败...");
        if (LoginType.JSON == securityPropertiese.getBrowser().getLoginType()){
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(exception.getMessage())));
        }else{
            super.onAuthenticationFailure(request, response, exception);
        }
    }
}
